'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { SyncStatus } from '@/components/dashboard/SyncStatus';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { API_ENDPOINTS } from '@/config/api';
import { useNetworkInfo, getExplorerUrl } from '@/hooks/useNetworkInfo';
import {
  Activity,
  ExternalLink,
  RefreshCw,
  Zap,
  Shield,
  Database,
  CheckCircle,
  AlertCircle,
  Info,
  TrendingUp,
  Coins,
  Users,
  Layers,
} from 'lucide-react';
import toast from 'react-hot-toast';

interface ContractInfo {
  token: {
    name: string;
    symbol: string;
    total_supply_formatted: string;
    mining_stats: {
      total_mining_formatted: string;
      total_claimed_formatted: string;
      remaining_reserve_formatted: string;
    };
  };
  nft: {
    name: string;
    symbol: string;
    max_supply: number;
    mining_bonus_percentage: number;
    current_price_formatted: string;
    stats: {
      total_minted: number;
      remaining_supply: number;
    };
  };
  vesting: {
    vesting_duration_months: number;
    stats: {
      total_schedules: number;
      total_vesting_formatted: string;
      total_released_formatted: string;
      contract_balance_formatted: string;
    };
    categories: Record<string, {
      limit_formatted: string;
      allocated_formatted: string;
      remaining_formatted: string;
    }>;
  };
  addresses: {
    dtv_token: string;
    dtv_nft: string;
    dtv_vesting: string;
  };
  network: string;
  latest_block: number;
}

interface MonitoringStatus {
  is_running: boolean;
  network: string;
  latest_block: number;
}

export default function BlockchainPage() {
  const { currentChain } = useChain();
  const [isStartingMonitoring, setIsStartingMonitoring] = useState(false);
  const [isStoppingMonitoring, setIsStoppingMonitoring] = useState(false);

  // Get network info for explorer URLs
  const { data: networkInfo } = useNetworkInfo();

  // Fetch contract information
  const { data: contractInfo, isLoading: contractLoading, refetch: refetchContract } = useQuery<ContractInfo>({
    queryKey: ['contractInfo', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.contracts.info);
      return response.data;
    },
    refetchInterval: 30000, // Refresh every 30 seconds
  });

  // Fetch monitoring status
  const { data: monitoringStatus, isLoading: monitoringLoading, refetch: refetchMonitoring } = useQuery<MonitoringStatus>({
    queryKey: ['monitoringStatus', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.contracts.admin.monitoringStatus);
      return response.data;
    },
    refetchInterval: 10000, // Refresh every 10 seconds
  });

  const handleStartMonitoring = async () => {
    setIsStartingMonitoring(true);
    try {
      const client = multiChainApi.getClient(currentChain);
      await client.get(API_ENDPOINTS.contracts.admin.monitoringStart);
      toast.success('Blockchain monitoring started');
      refetchMonitoring();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to start monitoring');
    } finally {
      setIsStartingMonitoring(false);
    }
  };

  const handleStopMonitoring = async () => {
    setIsStoppingMonitoring(true);
    try {
      const client = multiChainApi.getClient(currentChain);
      await client.get(API_ENDPOINTS.contracts.admin.monitoringStop);
      toast.success('Blockchain monitoring stopped');
      refetchMonitoring();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to stop monitoring');
    } finally {
      setIsStoppingMonitoring(false);
    }
  };

  const openInExplorer = (address: string) => {
    if (networkInfo && typeof networkInfo === 'object' && 'explorerUrl' in networkInfo) {
      window.open(`${networkInfo.explorerUrl}/address/${address}`, '_blank');
    } else {
      // Fallback to BSC testnet explorer
      window.open(`https://testnet.bscscan.com/address/${address}`, '_blank');
    }
  };

  if (contractLoading) {
    return (
      <DashboardLayout>
        <AdminGuard>
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        </AdminGuard>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold">Blockchain Management</h1>
              <p className="text-muted-foreground">
                Monitor and manage upgradeable DTV contracts
              </p>
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                onClick={() => {
                  refetchContract();
                  refetchMonitoring();
                }}
                className="flex items-center gap-2"
              >
                <RefreshCw className="h-4 w-4" />
                Refresh
              </Button>
            </div>
          </div>

          {/* 區塊鏈同步狀態 */}
          <SyncStatus />

          {/* Monitoring Controls */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Activity className="h-5 w-5" />
                監聽控制
              </CardTitle>
              <CardDescription>
                手動控制區塊鏈事件監聽服務
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-2">
                    {monitoringStatus?.is_running ? (
                      <CheckCircle className="h-5 w-5 text-green-600" />
                    ) : (
                      <AlertCircle className="h-5 w-5 text-red-600" />
                    )}
                    <span className="font-medium">
                      {monitoringStatus?.is_running ? '運行中' : '已停止'}
                    </span>
                  </div>
                  {monitoringStatus && (
                    <div className="text-sm text-muted-foreground">
                      區塊: {monitoringStatus.latest_block.toLocaleString()}
                    </div>
                  )}
                </div>
                <div className="flex gap-2">
                  {monitoringStatus?.is_running ? (
                    <Button
                      variant="danger"
                      onClick={handleStopMonitoring}
                      disabled={isStoppingMonitoring}
                    >
                      {isStoppingMonitoring ? (
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      ) : (
                        '停止監聽'
                      )}
                    </Button>
                  ) : (
                    <Button
                      onClick={handleStartMonitoring}
                      disabled={isStartingMonitoring}
                    >
                      {isStartingMonitoring ? (
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      ) : (
                        '開始監聽'
                      )}
                    </Button>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Contract Overview */}
          {contractInfo && (
            <>
              {/* Network Info */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Zap className="h-5 w-5" />
                    Network Information
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                      <p className="text-sm text-muted-foreground">Network</p>
                      <p className="font-medium capitalize">{contractInfo.network}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Latest Block</p>
                      <p className="font-medium">{contractInfo.latest_block.toLocaleString()}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Contract Type</p>
                      <p className="font-medium">UUPS Upgradeable</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Status</p>
                      <div className="flex items-center gap-1">
                        <CheckCircle className="h-4 w-4 text-green-600" />
                        <span className="font-medium text-green-600">Active</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Contract Addresses */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Database className="h-5 w-5" />
                    Contract Addresses
                  </CardTitle>
                  <CardDescription>
                    Deployed upgradeable contract addresses
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid gap-4">
                    <div className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h4 className="font-medium">DTV Token (Upgradeable)</h4>
                        <p className="text-sm text-muted-foreground font-mono">
                          {contractInfo.addresses.dtv_token}
                        </p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openInExplorer(contractInfo.addresses.dtv_token)}
                      >
                        <ExternalLink className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h4 className="font-medium">DTV NFT (Upgradeable)</h4>
                        <p className="text-sm text-muted-foreground font-mono">
                          {contractInfo.addresses.dtv_nft}
                        </p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openInExplorer(contractInfo.addresses.dtv_nft)}
                      >
                        <ExternalLink className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h4 className="font-medium">DTV Vesting (Upgradeable)</h4>
                        <p className="text-sm text-muted-foreground font-mono">
                          {contractInfo.addresses.dtv_vesting}
                        </p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openInExplorer(contractInfo.addresses.dtv_vesting)}
                      >
                        <ExternalLink className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Contract Statistics */}
              <div className="grid gap-6 md:grid-cols-3">
                {/* Token Stats */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Coins className="h-5 w-5" />
                      DTV Token
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div>
                      <p className="text-sm text-muted-foreground">Total Supply</p>
                      <p className="text-lg font-bold">{contractInfo.token.total_supply_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Mining</p>
                      <p className="font-medium">{contractInfo.token.mining_stats.total_mining_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Claimed</p>
                      <p className="font-medium">{contractInfo.token.mining_stats.total_claimed_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Remaining Reserve</p>
                      <p className="font-medium">{contractInfo.token.mining_stats.remaining_reserve_formatted} DTV</p>
                    </div>
                  </CardContent>
                </Card>

                {/* NFT Stats */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Shield className="h-5 w-5" />
                      DTV NFT
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div>
                      <p className="text-sm text-muted-foreground">Max Supply</p>
                      <p className="text-lg font-bold">{contractInfo.nft.max_supply}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Minted</p>
                      <p className="font-medium">{contractInfo.nft.stats.total_minted}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Remaining Supply</p>
                      <p className="font-medium">{contractInfo.nft.stats.remaining_supply}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Current Price</p>
                      <p className="font-medium">{contractInfo.nft.current_price_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Mining Bonus</p>
                      <p className="font-medium">{contractInfo.nft.mining_bonus_percentage}%</p>
                    </div>
                  </CardContent>
                </Card>

                {/* Vesting Stats */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Layers className="h-5 w-5" />
                      DTV Vesting
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div>
                      <p className="text-sm text-muted-foreground">Duration</p>
                      <p className="text-lg font-bold">{contractInfo.vesting.vesting_duration_months} months</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Schedules</p>
                      <p className="font-medium">{contractInfo.vesting.stats.total_schedules}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Vesting</p>
                      <p className="font-medium">{contractInfo.vesting.stats.total_vesting_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Released</p>
                      <p className="font-medium">{contractInfo.vesting.stats.total_released_formatted} DTV</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Contract Balance</p>
                      <p className="font-medium">{contractInfo.vesting.stats.contract_balance_formatted} DTV</p>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Vesting Categories */}
              <Card>
                <CardHeader>
                  <CardTitle>Vesting Categories</CardTitle>
                  <CardDescription>
                    Allocation status for each vesting category
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid gap-4 md:grid-cols-2">
                    {Object.entries(contractInfo.vesting.categories).map(([category, data]) => (
                      <div key={category} className="p-4 border rounded-lg">
                        <h4 className="font-medium capitalize mb-2">{category}</h4>
                        <div className="space-y-2">
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Limit</span>
                            <span>{data.limit_formatted} DTV</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Allocated</span>
                            <span>{data.allocated_formatted} DTV</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Remaining</span>
                            <span>{data.remaining_formatted} DTV</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                            <div
                              className="bg-blue-600 h-2 rounded-full"
                              style={{
                                width: `${
                                  (parseFloat(data.allocated_formatted) / 
                                   parseFloat(data.limit_formatted)) * 100
                                }%`
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}